<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="addRolesVisible = true">新增角色</el-button>
            <el-table
              :data="RoleData"
              border
              style="width: 100%;margin: 15px 0"
            >
              <el-table-column
                label="序号"
                type="index"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="180"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
              >
                <template v-slot="scope">
                  <el-button type="text" @click="setRight(scope.row.id)">分配权限</el-button>
                  <el-button type="text" @click="editRoleData(scope.row)">修改</el-button>
                  <el-button type="text" :disabled="isDisabled(point.rolesDel)" @click="delRoleData(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :current-page="queryData.page"
              :page-sizes="[2, 5, 10, 20]"
              :page-size="queryData.pagesize"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <el-row>
              <el-col :span="8" :offset="3">
                <el-form ref="form" label-width="80px">
                  <el-form-item label="企业名称">
                    <el-input v-model="company.name" disabled />
                  </el-form-item>
                  <el-form-item label="公司地址">
                    <el-input v-model="company.companyAddress" disabled />
                  </el-form-item>
                  <el-form-item label="公司电话">
                    <el-input v-model="company.companyPhone" disabled />
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <el-input v-model="company.mailbox" disabled />
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input v-model="company.remarks" disabled />
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 新增加角色的对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="addRolesVisible"
        width="30%"
        @close="addDialogClose"
      >
        <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="addForm.description" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRolesData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限的对话框 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightClose"
      >
        <el-tree
          ref="rightTree"
          :data="rightData"
          show-checkbox
          check-strictly
          default-expand-all
          node-key="id"
          icon-class=" "
          :props="defaultProps"
          :default-checked-keys="selectCheck"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRightSave">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getCompanyInfo } from '@/api/company.js'
import { getPermission } from '@/api/permission.js'
import { tranListToTree } from '@/utils/index.js'

// 引入mixins,混入 (mixin) 提供了一种非常灵活的方式，来分发 Vue 组件中的可复用功能。
import point from '@/mixins/point'

import {
  getRoleData,
  delRoleData,
  addRoleData,
  editRoleData,
  getRoleById,
  setRole
} from '@/api/role.js'
export default {
  mixins: [point],
  data() {
    return {
      activeName: 'first',
      company: {},
      RoleData: [],
      queryData: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      addRolesVisible: false,
      addForm: {
        name: '',
        description: ''
      },
      addRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限
      setRightDialogVisible: false,
      rightData: [],
      // 配置
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 默认选中的数组
      selectCheck: [],
      // 角色ID
      rightId: null
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },

  created() {
    // console.log(this.$store.getters.companyId)
    // 这里会出现一个小bug，刷新后打印的是undefiled而不是1，是因为在permission.js中发送请求获取用户数据的时候dispath返回的是promise，需要await把异步转为同步
    // console.log(this.companyId)
    this.getCompanyInfo()
    this.getRoleList()
  },

  methods: {
    // ^查询企业
    async getCompanyInfo() {
      const res = await getCompanyInfo(this.companyId)
      // console.log(res)
      this.company = res
    },
    // ^获取角色列表
    async getRoleList() {
      const res = await getRoleData(this.queryData)
      // console.log(res)
      this.RoleData = res.rows
      this.total = res.total
    },
    // ^重置表单
    addDialogClose() {
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        description: ''
      }
    },
    // ^添加角色
    async addRolesData() {
      try {
        // 表单校验的另一种形式，不传入回调，返回的是promise
        await this.$refs.addForm.validate()
        // 发起请求
        if (this.addForm.id) {
          // 修改
          // console.log('修改')
          await editRoleData(this.addForm)
          this.$message.success('更新角色成功')
        } else {
          // 添加
          await addRoleData(this.addForm)
          this.$message.success('添加角色成功')
        }
        this.addRolesVisible = false
        this.getRoleList()
      } catch (err) {
        this.$message.error('添加角色失败')
      }
    },
    // ^操作
    // 删除
    delRoleData(id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            await delRoleData(id)
            if (this.RoleData.length === 1) {
              this.queryData.page -= 1
            }
            this.$message.success('删除成功')
            this.getRoleList()
          } catch (err) {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击修改按钮
    editRoleData(row) {
      // console.log(row)
      this.addRolesVisible = true
      this.addForm = { ...row }
    },
    // ^分页
    // 监听每页的条数
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryData.pagesize = newSize
      this.getRoleList()
    },
    // 监听页码
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryData.page = newPage
      this.getRoleList()
    },
    // 点击分配权限按钮
    async setRight(id) {
      this.setRightDialogVisible = true
      // console.log(id)
      this.rightId = id
      const res = await getPermission()
      // console.log(res)
      // 处理数据结构
      this.rightData = tranListToTree(res, '0')
      // 获取员工的权限
      const { permIds } = await getRoleById(id)
      // console.log(permIds)
      this.selectCheck = permIds
    },
    // 弹出框关闭
    setRightClose() {
      this.selectCheck = []
      this.setRightDialogVisible = false
    },
    // 确定保存,分配权限
    async addRightSave() {
      // 获取选中的数组
      const arr = this.$refs.rightTree.getCheckedKeys()
      // console.log(arr)
      if (!arr.length) return this.$message.error('请选择权限')
      try {
        await setRole({ id: this.rightId, permIds: arr })
        this.$message.success('分配权限成功')
        this.setRightDialogVisible = false
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style scoped lang='less'>
::v-deep .el-tabs__header {
  .el-tabs__item {
    width: 140px;
    text-align: center;
  }
}
</style>
